package com.jcfk.system.service;

import com.jcfk.system.domain.po.SysMessageSendRecord;
import com.jcfk.system.domain.po.SysUser;
import com.jcfk.system.domain.query.SysMessageSendRecordQuery;
import com.jcfk.system.domain.dto.SysMessageSendRecordDTO;
import com.jcfk.system.domain.dto.SysMessageSendRecordDetailsDTO;
import com.jcfk.system.domain.po.SysMessageSendRecordDetails;
import com.jcfk.system.dao.SysMessageSendRecordDao;
import com.jcfk.system.dao.SysMessageSendRecordDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.ArrayList;
import java.util.List;

import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 消息发送记录
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2023-12-29
 */
@Service
public class SysMessageSendRecordService extends BaseService<SysMessageSendRecordDao, SysMessageSendRecord> {


    @Autowired
    private SysMessageSendRecordDetailsService sysMessageSendRecordDetailsService;


    @Autowired
    private SysUserService sysUserService;

    /**
     * SysMessageSendRecord分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysMessageSendRecordDTO> queryByPage(DataPage<SysMessageSendRecordDTO> page, SysMessageSendRecordQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        List<String> ids = page.getRecords().stream().map(SysMessageSendRecordDTO::getId).collect(Collectors.toList());
        if (ids.size() > 0) {
            QueryWrapper<SysMessageSendRecordDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("count(id) count, message_id messageId,message_status messageStatus").groupBy("message_status,message_id").in("message_id", ids);
            List<Map<String, Object>> maps = sysMessageSendRecordDetailsService.listMaps(queryWrapper);
            for (SysMessageSendRecordDTO record : page.getRecords()) {
                for (Map<String, Object> map : maps) {
                    if (record.getId().equals(map.get("messageId").toString()) && "1".equals(map.get("messageStatus").toString())) {
                        record.setReciveCount(map.get("count").toString());
                    }
                    if (record.getId().equals(map.get("messageId").toString()) && "2".equals(map.get("messageStatus").toString())) {
                        record.setReciveErrCount(map.get("count").toString());
                    }
                }
            }
        }

        return page;
    }

    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<SysMessageSendRecordDTO>
     */
    public List<SysMessageSendRecordDTO> getList(SysMessageSendRecordQuery query) {
        // 查询条件
        QueryWrapper<SysMessageSendRecord> qw = new QueryWrapper<>();
        // 查询数据
        List<SysMessageSendRecord> list = super.list(qw);

        return convertList(list, SysMessageSendRecordDTO.class);
    }

    /**
     * 获取根据关联id详情表列表
     *
     * @param query 查询条件
     * @return List<SysMessageSendRecordDTO>
     */
    public List<SysMessageSendRecordDetailsDTO> getDetails(SysMessageSendRecordQuery query) {
        // 查询条件
        QueryWrapper<SysMessageSendRecordDetails> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getId()), SysMessageSendRecordDetails::getMessageId, query.getId());

        // 查询数据
        List<SysMessageSendRecordDetails> list = sysMessageSendRecordDetailsService.list(qw);
        List<SysMessageSendRecordDetailsDTO> ret = convertList(list, SysMessageSendRecordDetailsDTO.class);
        List<String> ids = new ArrayList<>();
        for (SysMessageSendRecordDetails details : list) {
            if (!StringUtils.isEmpty(details.getRecevieUserId())) ids.add(details.getRecevieUserId());
        }

        if (ids.size() > 0) {
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.in("id", ids);
            List<SysUser> users = sysUserService.list(sysUserQueryWrapper);
            for (SysMessageSendRecordDetailsDTO details : ret) {
                for (SysUser user : users) {
                    if (details.getRecevieUserId() != null && details.getRecevieUserId().equals(user.getId())) {
                        details.setRecevieUserName(user.getFirstName());
                    }
                }
            }
        }


        return ret;
    }


    /**
     * 判断SysMessageSendRecord是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysMessageSendRecordDTO dto) {
        QueryWrapper<SysMessageSendRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", dto.getId());

        return RetResult.ok();
    }

    /**
     * 插入消息发送记录
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysMessageSendRecordDTO dto) {

        // 保存
        SysMessageSendRecord item = new SysMessageSendRecord();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);

        // 设置关联主键
        for (SysMessageSendRecordDetailsDTO detail : dto.getDetails()) {
            detail.setMessageId(item.getId());
        }

        // 保存明细表
        sysMessageSendRecordDetailsService.saveBatch(dto.getDetails());
    }


    /**
     * 更新消息发送记录
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SysMessageSendRecordDTO dto) {

        // 保存
        SysMessageSendRecord item = new SysMessageSendRecord();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);

        // 设置关联主键
        for (SysMessageSendRecordDetailsDTO detail : dto.getDetails()) {
            detail.setMessageId(dto.getId());
        }
        // 保存明细表
        sysMessageSendRecordDetailsService.saveBatch(dto.getDetails());
    }


    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysMessageSendRecord item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreatedUserName(SecurityUtils.getUserName());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
    }


    /**
     * 根据主键获取消息发送记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysMessageSendRecordDTO get(String id) {
        // 查询数据
        SysMessageSendRecord item = this.baseMapper.selectById(id);
        SysMessageSendRecordDTO dto = new SysMessageSendRecordDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }
}

